package com.epoch.platform.sys.job.controller;

import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;

import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.constant.Constant;
import com.epoch.base.schedule.QuartzKit;
import com.epoch.base.util.AjaxResult;
import com.epoch.base.util.JSONUtils;
import com.epoch.base.util.LoggerUtil;
import com.epoch.platform.sys.job.dao.SysScheduleJob;
import com.jfinal.core.Controller;

@ControllerBind(controllerKey = "/schedule")
public class ScheduleController extends Controller {
	
	private AjaxResult ajaxResult = new AjaxResult();

    /**
     * 初始化加载定时任务
     * 查询所有的定时任务
     */
    public void scheduleInit() {
        SysScheduleJob model = getModel(SysScheduleJob.class);
        String sql = "select * from sys_schedule_job where 1=1 ";
        if (model != null) {
            String jobName = model.getStr(SysScheduleJob.JOB_NAME);
            String jobGroup = model.getStr(SysScheduleJob.JOB_GROUP);
            String jobStatus = model.getStr(SysScheduleJob.JOB_STATUS);
            if (StringUtils.isNotBlank(jobName)) {
                sql += SysScheduleJob.JOB_NAME + " = '" + jobName + "'";
            }
            if (StringUtils.isNotBlank(jobGroup)) {
                sql += SysScheduleJob.JOB_GROUP + " = '" + jobGroup + "'";
            }
            if (StringUtils.isNotBlank(jobStatus)) {
                sql += SysScheduleJob.JOB_STATUS + " = '" + jobStatus + "'";
            }
        }
        renderJson(ajaxResult.success(SysScheduleJob.dao.find(sql)));
    }
    
    /**
     * 暂停任务
     */
    public void scheduleStop() {
        String scheduleId = getPara("id");
        SysScheduleJob sysScheduleJob = SysScheduleJob.dao.findById(scheduleId);
        try {
            JobKey jobKey = JobKey.jobKey(sysScheduleJob.getStr(SysScheduleJob.JOB_NAME), sysScheduleJob.getStr(SysScheduleJob.JOB_GROUP));
            Scheduler scheduler = QuartzKit.getSchedulerFactory().getScheduler();
            scheduler.pauseJob(jobKey);
            //更新任务状态
            sysScheduleJob.set(SysScheduleJob.JOB_STATUS, Constant.JOB_STATUS_1);
            sysScheduleJob.update();
            ajaxResult.success("暂停成功。");
        } catch (SchedulerException e) {
            ajaxResult.addError("暂停失败。");
        }
        renderJson(ajaxResult);
    }
    
    /**
     * 删除任务
     */
    public void deleteSchedule(){
        String[] ids = getParaValues("ids[]");
        if (ArrayUtils.isNotEmpty(ids)) {
            for (String id : ids) {
                SysScheduleJob sysScheduleJob = SysScheduleJob.dao.findById(id);
                String jobName = sysScheduleJob.getStr(SysScheduleJob.JOB_NAME);
                String jobGroup = sysScheduleJob.getStr(SysScheduleJob.JOB_GROUP);
                try {
                    TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
                    Scheduler scheduler = QuartzKit.getSchedulerFactory().getScheduler();
                    scheduler.pauseTrigger(triggerKey);// 停止触发器
                    scheduler.unscheduleJob(triggerKey);// 移除触发器
                    JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
                    scheduler.deleteJob(jobKey);// 删除任务
                    SysScheduleJob.dao.deleteById(id);
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * 立即执行
     */
    public void triggerJob(){
        String scheduleId = getPara("id");
        String params=getPara("param");
        Map s=null;
        try{
        	s=JSONUtils.stringToCollect(params);
        }catch(Exception e){
        	LoggerUtil.getLogger().error("-##triggerJob scheduleId:" + scheduleId + " 恢复失败，" + e);
        }
        SysScheduleJob sysScheduleJob = SysScheduleJob.dao.findById(scheduleId);
        String jobName = sysScheduleJob.getStr(SysScheduleJob.JOB_NAME);
        String jobGroup = sysScheduleJob.getStr(SysScheduleJob.JOB_GROUP);
        JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
        JobDataMap jobData=new JobDataMap();
        if(s!=null){
        	jobData.putAll(s);
        }
        Scheduler scheduler;
        try {
            scheduler = QuartzKit.getSchedulerFactory().getScheduler();
            scheduler.triggerJob(jobKey,jobData);
            ajaxResult.success("立即执行任务成功。");
        } catch (SchedulerException e) {
            ajaxResult.addError("立即执行任务失败。");
        }
        renderJson(ajaxResult);
    }

    /**
     * 恢复任务
     */
    public void scheduleResume() {
        String scheduleId = getPara("id");
        SysScheduleJob sysScheduleJob = SysScheduleJob.dao.findById(scheduleId);
        try {
            String jobName = sysScheduleJob.getStr(SysScheduleJob.JOB_NAME);
            String jobGroup = sysScheduleJob.getStr(SysScheduleJob.JOB_GROUP);
            Scheduler scheduler = QuartzKit.getSchedulerFactory().getScheduler();
            if (Constant.JOB_STATUS_1.equals(sysScheduleJob.getStr(SysScheduleJob.JOB_STATUS))) {
                JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
                scheduler.resumeJob(jobKey);
            } else {
                TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
                CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
                if (null == trigger) {
                    JobDetail jobDetail = JobBuilder.newJob(
                            (Class<? extends Job>) Class.forName(sysScheduleJob.getStr(SysScheduleJob.TARGET_CLASS)).newInstance().getClass())
                            .withIdentity(jobName, jobGroup).build();
                    jobDetail.getJobDataMap().put("scheduleJob", sysScheduleJob);
                    // 表达式调度构建器
                    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(sysScheduleJob.getStr(SysScheduleJob.CRON_EXPRESSION));
                    // 按新的cronExpression表达式构建一个新的trigger
                    trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup).withSchedule(scheduleBuilder).build();
                    scheduler.scheduleJob(jobDetail, trigger);
                } else {
                    // Trigger已存在，那么更新相应的定时设置
                    // 表达式调度构建器
                    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(sysScheduleJob.getStr(SysScheduleJob.CRON_EXPRESSION));
                    // 按新的cronExpression表达式重新构建trigger
                    trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder)
                            .build();
                    // 按新的trigger重新设置job执行
                    scheduler.rescheduleJob(triggerKey, trigger);
                }
            }
            //更新任务状态
            //Db.update("UPDATE SYS_SCHEDULE_JOB SET JOB_STATUS = ? WHERE  ID=?", ScheduleConstant.JOB_STATUS_0,scheduleId);
            sysScheduleJob.set(SysScheduleJob.JOB_STATUS, Constant.JOB_STATUS_0);
            sysScheduleJob.update();
            ajaxResult.success("启动任务成功。");
        } catch (Exception e) {
            ajaxResult.addError("启动任务失败。");
        }
        renderJson(ajaxResult);
    }
}
